package com.scut.online_black_market.utility;

import com.scut.online_black_market.exception.FileUploadException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.Future;

/**
 * create by yellowBroke on 2020年10月15日 00点42分
 * 图片上传
 */

@Component
public class ImageUtil {

    @Value("${images.dir.path}")
    private String imagePath;

    @Value("${ip.address}")
    private String ipAddress;

    @Value("${images.dir.port}")
    private String port;

    /**
     *
     * @param image 图片文件
     * @return imageUrl 图片路径
     * @throws FileUploadException
     */
    @Async
    public Future<String> saveImage(MultipartFile image) throws FileUploadException {

        if (image == null || image.isEmpty()) {
            throw new FileUploadException("图片不可为空！");
        }

        //获取文件后缀名
        String extendName = Objects.requireNonNull(image.getOriginalFilename()).split("\\.")[1];
        String fileName = UUID.randomUUID().toString().replace("-","") + "." + extendName;
        String destFileName = imagePath + File.separator + fileName;
        File destFile = new File(destFileName);

        try {
            image.transferTo(destFile);
        } catch (IOException e) {
            throw new FileUploadException("I/O内部错误！");
        }

        String imageUrl = "http://" + ipAddress + ":" + port + "/image/" + fileName;

        return new AsyncResult<>(imageUrl);
    }
}
